package com.lyc.user.servceImpl;

import com.lyc.user.bean.User;
import com.lyc.user.dao.UserDao;
import com.lyc.user.daoImpl.UserDaoImpl;
import com.lyc.user.service.UserService;
import com.lyc.user.util.ConfiUtil;
import com.lyc.user.util.DateUtil;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class UserServiceImpl implements UserService {
private 	UserDao userDao = new UserDaoImpl();
	/**
	 * 业务层，通过判断用户的账户和密码是否匹配，验证登录是否成功
	 */
	@Override
	public User accountLogin(User user) {
		User u = userDao.getUserByAccount(user.getAccount());

		return u;
	}

//	@Test
// public void lo(){
//		User user=new User();
//		user.setAccount("123");
//	 UserService userService = new UserServiceImpl();
//	 userService.accountLogin(user);
// }

	/**
	 * 业务层 短信验证码发送
	 *
	 * @param phone
	 * @return
	 */
	// accountSid=a14f6bfd43ce44c9b019de57f4e2de4b&smsContent=【秒嘀科技】您的验证码是345678，30分钟输入有效。
	//  &to=13896543210&timestamp=20150821100312&sig=a14f6bfd43ue44c9b019du57f4e2ee4r&respDataType=JSON
	@Override
	public String smsSend(String phone) {
		//定义获取的随机验证码 6位
		int veriCode = (int) (Math.random() * (999999 - 100000 + 1)) + 100000;
		//定义短信的内容
		String smsContent = "【远远科技】您的验证码为" + veriCode + "，请于10分钟内正确输入，如非本人操作，请忽略此短信。";
		System.out.println(smsContent);
		//定义时间戳
		String timestamp = DateUtil.DatoToString(new Date(), "yyyyMMddHHmmss");
		//定义sin签名 MD5加密(ACCOUNT SID + AUTH TOKEN + timestamp)
		String sig = sign(timestamp);
		//定义返回的类型为JSON
		String respDataType = "JSON";
		//封装参数
		String parameter = getParameter(phone, smsContent, timestamp, sig, respDataType);

		//调用秒滴的短信接口
		try {
			send(parameter);
			System.out.println(	send(parameter));
			String result=	"{\"respCode\":\"00000\",\"respDesc\":\"请求成功。\",\"failCount\":\"0\",\"failList\":[],\"smsId\":\"2a5c4368cdff47b2b690f842ebd74280\"}";
			JSONObject jsonObject = JSONObject.fromObject(result);
			Object respCode = jsonObject.get("respCode");
			  if (respCode.equals("00000")){
		    // 把发送成功的验证码存入数据库中
			  	   if (changePhonePwd(phone,veriCode+"")){
			  	   	return "短信发送成功";
				   }
			  	   return "短信发送失败";
			  }
			return "短信发送失败";

		} catch (Exception e) {
			e.printStackTrace();
		}
			return null;
	}

	/**
	 * sig签名方法  MD5加密(ACCOUNT SID + AUTH TOKEN + timestamp)
	 *
	 * @param timestamp
	 * @return
	 */
	public String sign(String timestamp) {
		String ACCOUNT_SID = ConfiUtil.ACCOUNT_SID;
		String AUTH_TOKEN = ConfiUtil.AUTH_TOKEN;
		return DigestUtils.md5Hex(ACCOUNT_SID + AUTH_TOKEN + timestamp);
	}

	/**
	 * 封装参数
	 *
	 * @param phone
	 * @param smsContent
	 * @param timestamp
	 * @param sig
	 * @param respDataType
	 * @return
	 */
	public String getParameter(String phone, String smsContent, String timestamp, String sig, String respDataType) {
		StringBuffer sb = new StringBuffer();
		sb.append("accountSid=").append(ConfiUtil.ACCOUNT_SID)
				.append("&smsContent=").append(smsContent)
				.append("&to=").append(phone)
				.append("&timestamp=").append(timestamp)
				.append("&sig=").append(sig)
				.append("&respDataType=").append(respDataType);
		return sb.toString();
	}

	/**
	 * 短信发送
	 *
	 * @return
	 */

	public String send(String parameter) throws Exception {
		//定义一个URL对象
		URL url = new URL(ConfiUtil.URL);
		//打开连接
		URLConnection urlconn = url.openConnection();
		//设置连接的参数
		urlconn.setConnectTimeout(2000);
		urlconn.setDoInput(true);
		urlconn.setDoOutput(true);
		//从连接中输出流
		OutputStream os = urlconn.getOutputStream();
		//将字节流转换为字符流
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
		//把参数发给秒滴
		bw.write(parameter);
		//刷新流
		bw.flush();
		//获得秒滴的返回结果
		InputStream is = urlconn.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		//读出数据
		StringBuffer sb = new StringBuffer();
		String line = "";
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		//关闭流
		br.close();
		is.close();
		bw.close();
		os.close();
		return sb.toString();
	}

	/**
	 * 修改验证码，（将验证码储存到数据库中）
	 *
	 * @param phone
	 * @param veriCode
	 * @return
	 */
	@Override
	public boolean changeVeriCode(String phone, Integer veriCode) {
		return userDao.changeVeriCode(phone, veriCode) > 0 ? true : false;
	}

	/**
	 * 用户手机号登陆
	 *
	 * @param user
	 * @return
	 */
	@Override
	public String phoneLogin(User user) {
		User use = userDao.getUserByPhone(user.getPhone());
		if (use == null) {
			return "手机号码为空";
		} else if (!(use.getVeriCode().equals(user.getVeriCode()))) {
			return "输入的验证码错误";
		} else if (new Date().getTime() > use.getVericodeTime().getTime()) {
			return "验证码已失效";
		}
		//登录过后，让收到的验证码失效
		changeVeriCode(user.getPhone(), 0);
		return "登录成功";
	}

	/**
	 * 用户账户注册时在数据库中插入账户和密码
	 * @param account
	 * @param pwd
	 * @return
	 */
	@Override
	public boolean changeAccountRegister(String account, String pwd) {
		return userDao.changeAccountRegister(account,pwd) >0 ?true : false;
	}

	/**
	 * 用户账号注册
	 * @param user
	 * @return
	 */
	@Override
	public String userAccountRegister(User user) {
		User u= userDao.getUserByAccount(user.getAccount());
		if (u==null){
			int i = userDao.changeAccountRegister(user.getAccount(), user.getPwd());
			return ( i!=0 ? "账户注册成功":"账户注册失败");
		}else {
			return "账户已经存在";
		}

	}

	/**
	 * 注册时修改电话号码,密码,验证码
	 *
	 * @param phone
	 * @param veriCode
	 * @return
	 */
	@Override
	public boolean changePhonePwd(String phone,String veriCode) {
		int row = userDao.changePhonePwd(phone,veriCode);
		return row > 0 ? true : false;
	}

	/**
	 * 用户通过手机号注册账号，先判断数据库中是否存在该手机号，如果不存在则进行注册
	 *
	 * @param user
	 * @return
	 */
	@Override
	public String phoneRegister(User user) {
		User u = userDao.getUserByPhone(user.getPhone());
	     if (u==null){
			 int i = userDao.changePhonePwd(user.getPhone(),user.getVeriCode());
			  if (i>0){
					if (!(u.getVeriCode().equals(user.getVeriCode()))){
						return "验证码错误";
					}else {
						return "电话号码注册成功";
					}
			  }else{
			  	return "电话号码注册失败";
			  }
		 }else {
			 //注册过后，让收到的验证码失效
			 changeVeriCode(user.getPhone(), 0);
			 return "该电话号码已经注册过";
		 }
	}
}